/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.lestr.udm.core.impl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.lestr.udm.core.api.*;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author pibonnin
 */
public class RAMDataManager implements IDataManager {


    private Map<String, Data> datas;


    public RAMDataManager() {

        datas = new HashMap<String, Data>();

    }// END Constructor


    @Override
    public ISession openSession() {

        return new Session();

    }// END Method openSession


    private class Session implements ISession {


        @Override
        public void addData(String id) {

            datas.put(id, new Data());

        }// END Method addData


        @Override
        public void setDataTypes(String id,
                                 List<IDataType> types) {

            datas.get(id).types = types;

        }// END Method setDataTypes


        @Override
        public List<IDataType> getDataTypes(String id) {

            return datas.get(id).types;

        }// END Method getDataTypes


        @Override
        public void setDataValue(String id,
                                 InputStream value) {
            
            try {

                int nbRead;
                byte[] buffer = new byte[1024];
                ByteArrayOutputStream out = new ByteArrayOutputStream();

                while ((nbRead = value.read(buffer)) > 0)
                    out.write(buffer, 0, nbRead);

                value.close();

                datas.get(id).value = out.toByteArray();

            } catch (IOException ex) {
                Logger.getLogger(RAMDataManager.class.getName()).log(Level.SEVERE, null, ex);
            }

        }// END Method setDataValue


        @Override
        public InputStream getDataValue(String id) {

            return new ByteArrayInputStream(datas.get(id).value);

        }// END Method getDataValue


        @Override
        public void commit() {
        }// END Method commit


        @Override
        public void close() {
        }// END Method close


    }// FIN Classe ISession


    private static class Data {


        private List<IDataType> types;


        private byte[] value;


    }// END class Data


}// END Class DataManager
